package com.crdeng.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crdeng.business.entity.*;
import com.crdeng.business.mapper.OutStockInfoMapper;
import com.crdeng.business.mapper.OutStockMapper;
import com.crdeng.business.mapper.ProductStockMapper;
import com.crdeng.business.service.ConsumerService;
import com.crdeng.business.service.OutStockService;
import com.crdeng.business.service.ProductService;
import com.crdeng.business.vo.*;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.ResultCode;
import com.crdeng.system.vo.UserRoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author crdeng
 * @since 2021-02-06
 */
@Transactional
@Service
public class OutStockServiceImpl extends ServiceImpl<OutStockMapper, OutStock> implements OutStockService {

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private OutStockInfoMapper outStockInfoMapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductStockMapper productStockMapper;


    @Override
    public IPage<OutStockVO> findOutStock(Integer pageNun, Integer pageSize, outStocksQueryMap queryMap) {
        Page<OutStockVO> page = new Page<>(pageNun, pageSize);
        QueryWrapper<OutStockVO> outStockQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryMap.getOutNum())) {
            outStockQueryWrapper.like("os.out_num", queryMap.getOutNum());
        }

        if (queryMap.getStatus() != null) {
            outStockQueryWrapper.like("os.status", queryMap.getStatus());
        }

        if (queryMap.getType() != null) {
            outStockQueryWrapper.like("os.type", queryMap.getType());
        }
        IPage<OutStockVO> outStockList = baseMapper.findOutStockList(page, outStockQueryWrapper);

        return outStockList;
    }

    @Override
    public OutStockDetailVO getDetail(Long id, Integer pageNum, Integer pageSize) {
        OutStock byId = getById(id);
        if (byId == null) {
            throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(), "入库单不存在");
        }
        OutStockDetailVO detailVO = new OutStockDetailVO();
        BeanUtils.copyProperties(byId, detailVO);
        //获取用户信息
        Consumer consumer = consumerService.getById(byId.getConsumerId());
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer, consumerVO);
        detailVO.setConsumerVO(consumerVO);
        Page<OutStockItemVO> outStockItemVOPage = new Page<>(pageNum, pageSize);
        QueryWrapper<OutStockItemVO> outStockItemVOQueryWrapper = new QueryWrapper<>();
        outStockItemVOQueryWrapper.eq("os.out_num", byId.getOutNum());
        IPage<OutStockItemVO> stockInfo = outStockInfoMapper.getOutStocks(outStockItemVOPage, outStockItemVOQueryWrapper);
        detailVO.setTotal(stockInfo.getTotal());
        List<OutStockItemVO> records = stockInfo.getRecords();
        records.forEach((item) -> {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("p_num", item.getPNum());
            Product one = productService.getOne(queryWrapper);
            BeanUtils.copyProperties(one, item);
        });
        detailVO.setItemVOS(records);
        return detailVO;
    }

    /**
     * 更改入库单状态
     *
     * @param id
     * @param statusNum
     */
    @Override
    public void alterStatus(Long id, Integer statusNum) {
        OutStock byId = getById(id);
        if (byId == null) {
            throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(), "出库单不存在");
        }
        ;
        byId.setStatus(statusNum);
        updateById(byId);
    }

    /*添加出库单*/
    @Override
    public void addOutStock(OutStockVO outStockVO) {
        //随机生成发放单号
        String OUT_STOCK_NUM = UUID.randomUUID().toString().substring(0, 32).replace("-", "");
        int itemNumber = 0;//记录该单的总数
        //获取商品的明细
        List<Object> products = outStockVO.getProducts();

        if (!CollectionUtils.isEmpty(products)) {
            for (Object product : products) {
                LinkedHashMap item = (LinkedHashMap) product;
                //发放数量
                int productNumber = (int) item.get("productNumber");
                //物资编号
                Integer productId = (Integer) item.get("productId");
                Product dbProduct = productService.getById(productId);
                if (dbProduct == null) {
                    throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(), "物资不存在");
                } else if (productNumber <= 0) {
                    throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), dbProduct.getName() + "发放数量不合法,无法入库");
                } else {
                    //校验库存
                    QueryWrapper<ProductStock> productStockQueryWrapper = new QueryWrapper<>();
                    productStockQueryWrapper.eq("p_num", dbProduct.getPNum());
                    ProductStock productStock = productStockMapper.selectOne(productStockQueryWrapper);
                    if (productStock == null) {
                        throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), "该物资在库存中不存在");
                    }
                    if (productNumber > productStock.getStock()) {
                        throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), dbProduct.getName() + "库存不足,库存剩余:" + productStock);
                    }
                    itemNumber += productNumber;
                    //入库单明细
                    OutStockInfo outStockInfo = new OutStockInfo();
                    outStockInfo.setCreateTime(new Date());
                    outStockInfo.setModifiedTime(new Date());
                    outStockInfo.setProductNumber(productNumber);
                    outStockInfo.setPNum(dbProduct.getPNum());
                    outStockInfo.setOutNum(OUT_STOCK_NUM);
                    outStockInfoMapper.insert(outStockInfo);

                    productStock.setStock(productStock.getStock()-productNumber);
                    productStockMapper.updateById(productStock);


                }
            }
            OutStock outStock = new OutStock();
            BeanUtils.copyProperties(outStockVO, outStock);
            outStock.setCreateTime(new Date());
            outStock.setProductNumber(itemNumber);
            UserRoleVO userRoleVO = (UserRoleVO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            outStock.setOperator(userRoleVO.getUsername());
            //生成入库单
            outStock.setOutNum(OUT_STOCK_NUM);
            //设置为待审核
            outStock.setStatus(2);
            baseMapper.insert(outStock);
        } else {
            throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), "创建出库单失败");
        }

    }

}
